package de.baumann.browser.fragments;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextSwitcher;
import android.widget.TextView;


import org.jetbrains.annotations.NotNull;

import java.math.BigDecimal;
import java.util.List;

import de.baumann.browser.BuildConfig;
import de.baumann.browser.R;
import de.baumann.browser.activitys.NoticeActivity;
import de.baumann.browser.activitys.hash.MiningIncomeActivity;
import de.baumann.browser.activitys.hash.RedPacketActivity;
import de.baumann.browser.api.net.vo.Notice;
import de.baumann.browser.api.net.vo.OdinOre;
import de.baumann.browser.base.BaseOdinFragment;
import de.baumann.browser.iview.IMiningView;
import de.baumann.browser.present.MiningPresenterNew;
import de.baumann.browser.utils.CountTimer;
import de.baumann.browser.utils.StringUtil;
import de.baumann.browser.utils.UserDataKt;
import de.baumann.browser.utils.ViewUtil;
import de.baumann.browser.utils.web3j.BalancePowerTask;
import de.baumann.browser.utils.web3j.MyPowerTask;
import de.baumann.browser.views.widget.AntForestView;
import de.baumann.browser.views.dialog.GatherGlodDialog;

import static de.baumann.browser.utils.Constants.LOGINCODE;

/**
 * @author:
 * @date:2018/12/6 11:04
 * @discription: 挖矿页面
 */
@SuppressWarnings("ALL")
public class MiningFragment extends BaseOdinFragment<IMiningView, MiningPresenterNew> implements
        IMiningView,
        AntForestView.OnBallClickListener {

    private ImageView ivMiningHead;
    private TextView mTvHashValue;
    private TextView mTvTotalHash;
    private TextSwitcher mTvSwitcher;
    private TextView tvMiningAddress;


    private String odinValue = "0.0000";
    private String hashValue = "0.0000";


    private TextView tvTime;
    private FrameLayout bannerContainer;

    private static MiningFragment instance = null;


    public MiningFragment() {
        bindEth = UserDataKt.getMoneyAddress();
    }

    public static MiningFragment getInstance() {
        synchronized (MiningFragment.class) {
            if (instance == null) {
                instance = new MiningFragment();
            }
        }
        return instance;
    }

    @Override
    public int getLayout() {
        return R.layout.fragment_mining;
    }

    @SuppressWarnings("AliDeprecation")
    @Override
    public void initView(View view) {
        view.findViewById(R.id.miningScroll).setPadding(0, ViewUtil.getStatusBarHeight(mContext), 0, 0);
        ivMiningHead = view.findViewById(R.id.ivMiningHead);
        mTvHashValue = view.findViewById(R.id.tvHashValue);
        mTvTotalHash = view.findViewById(R.id.tvTotalHash);
        mTvSwitcher = view.findViewById(R.id.tvNotice);
        tvMiningAddress = view.findViewById(R.id.tvMiningAddress);
        mTvSwitcher.setFactory(() -> {
            TextView textView = new TextView(mContext);
            Drawable drawable = getResources().getDrawable(R.drawable.icon_notice);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            textView.setCompoundDrawables(drawable, null, null, null);
            textView.setCompoundDrawablePadding(10);
            textView.setTextColor(mContext.getResources().getColor(R.color.windowLight));
            textView.setSingleLine(true);
            textView.setEllipsize(TextUtils.TruncateAt.END);
            return textView;
        });
        mTvSwitcher.setOnClickListener(view12 -> startActivity(new Intent(mContext, NoticeActivity.class)));


        tvTime = view.findViewById(R.id.tvTime);
        view.findViewById(R.id.rlMiningIncome).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MiningIncomeActivity.Companion.startMiningIncomeActivity(mContext);
            }
        });

        bannerContainer = view.findViewById(R.id.banner_container);

       /* view.findViewById(R.id.miningRedPack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RedPacketActivity.Companion.startRedPacketActivity(mContext);
            }
        });*/
    }

    private String bindEth = null;

    @Override
    public void onResume() {
        super.onResume();
        bindEth = UserDataKt.getMoneyAddress();
        getPresenter().getAirDropTime();
        bindEth = UserDataKt.getMoneyAddress();
        if (UserDataKt.getMoneyAddress() != "") {
            if (bindEth.startsWith("0x")) {
                bindEth = "od" + bindEth.substring(1);
            }
            tvMiningAddress.setText(StringUtil.StrReplace(bindEth));
            if (!UserDataKt.getIsLogin()) {
                getPresenter().login();
            }
            handler.sendEmptyMessageDelayed(1, 200);
            new MyPowerTask(mTvHashValue, BuildConfig.WALLET_NODE_URL, BuildConfig.BUY_HASH_ADDRESS, UserDataKt.getMoneyAddress()).execute();
        } else {
            showLoginDialog();
        }
        //        }

    }

    @Override
    public void initData() {

    }


  /*  private void bindDislikeAction(CNativeAd ad, View dislikeView) {
        final CAdDislike ttAdDislike = ad.getDislikeDialog(this.getActivity());
        if (ttAdDislike != null) {
            ttAdDislike.setDislikeInteractionCallback(new CAdDislike.CDislikeInteractionCallback() {
                @Override
                public void onSelected(int position, String value) {
                    bannerContainer.removeAllViews();
                }

                @Override
                public void onCancel() {

                }

                @Override
                public void onRefuse() {

                }
            });
        }
        dislikeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ttAdDislike != null){
                    ttAdDislike.showDislikeDialog();
                }
            }
        });
    }
*/

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LOGINCODE && resultCode == Activity.RESULT_OK) {
//            initData();
            refreshData();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    getPresenter().getOdinAndHashValue();
                    break;
                case 3:
//                    getPresenter().getNotice();
                    break;
                default:
            }
        }
    };


    @Override
    public void onNewIntent() {

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setOdinValue(String odinValue) {
        this.odinValue = odinValue;
    }

    @Override
    public void setTotalHash(String totalHash) {
        BigDecimal bigDecimal = new BigDecimal(totalHash);
        mTvTotalHash.setText("全网算力值  " + bigDecimal.setScale(4, BigDecimal.ROUND_HALF_UP).toString());
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setHashValue(String hashValue) {
        this.hashValue = hashValue;
        BigDecimal bigDecimal = new BigDecimal(hashValue);
        mTvHashValue.setText("当前算力值  " + bigDecimal.setScale(4, BigDecimal.ROUND_HALF_UP).toString());
    }

    public void refreshData() {
        getPresenter().getOdinAndHashValue();
    }

    @Override
    public void setOdinOre(List<OdinOre> odinOre) {
    }

    private int lockStatus = 0;

    private int i = 1;
    private List<Notice> noticeList;

    @Override
    public void setNotices(@NotNull List<? extends Notice> notices) {
        if (notices == null || notices.size() <= 0) {
            mTvSwitcher.setVisibility(View.INVISIBLE);
            return;
        }
        mTvSwitcher.setVisibility(View.VISIBLE);

        if (notices.size() > 5) {
            noticeList = (List<Notice>) notices.subList(0, 4);
        } else {
            noticeList = (List<Notice>) notices;
        }
        timeHandler.removeCallbacks(runnable);
        final String notice = notices.get(0).getNoticeTitle();
        mTvSwitcher.setText(notice);
        mTvSwitcher.setTag(0);
        i = 1;
        timeHandler.postDelayed(runnable, 2000);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (i < noticeList.size()) {
                mTvSwitcher.setText(noticeList.get(i).getNoticeTitle());
                mTvSwitcher.setTag(i);
            } else {
                mTvSwitcher.setText(noticeList.get(i % noticeList.size()).getNoticeTitle());
                mTvSwitcher.setTag(i % noticeList.size());
            }
            i++;
            timeHandler.postDelayed(this, i * 2000);
        }
    };

    private TimeHandler timeHandler = new TimeHandler();

    private GatherGlodDialog adDialog;

    @Override
    public void onBallClick(View view, OdinOre odinOre, int position) {

        String adBlock = odinOre.getAdBlock();
        if (adDialog != null && adDialog.isShowing()) {
            return;
        }

//        showGatherGlodDialog(view, odinOre, position);
    }

//    void showGatherGlodDialog(View view, OdinOre odinOre, int position) {
//
//        adDialog = new GatherGlodDialog(mContext, odinOre.getOreValue(), new GatherGlodDialog.OnElementClickListener() {
//            @Override
//            public void clickButton() {
//                String odin = odinOre.getOreValue();
//                BigDecimal bigOdin = new BigDecimal(odinValue).add(new BigDecimal(odin));
//                setOdinValue(bigOdin.toString());
//                getPresenter().gatherOre(odinOre);
//            }
//        });
//        adDialog.show();
//    }

    @NotNull
    @Override
    public MiningPresenterNew createPresenter() {
        return new MiningPresenterNew();
    }

    @NotNull
    @Override
    public IMiningView createView() {
        return this;
    }

    private static class TimeHandler extends Handler {

    }

    private CountTimer countTimer;

    @Override
    public void setTime(long time) {
        countTimer = new CountTimer(tvTime, time);
        countTimer.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (countTimer != null) {
            countTimer.cancel();
        }
    }
}
